package com.training.base;

import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;

@ControllerAdvice
public class GlobalExceptionHandler {

    @Autowired
    private Gson gson;

    /**
     * 处理自定义业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<String> handleBusinessException(BusinessException ex, WebRequest request) {
        Result<Object> result = Result.fail(ex.getCode(), ex.getMessage());
        return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
    }

    /**
     * 处理参数验证异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<String> handleIllegalArgumentException(IllegalArgumentException ex, WebRequest request) {
        Result<Object> result = Result.fail(400, "参数错误: " + ex.getMessage());
        return new ResponseEntity<>(gson.toJson(result), HttpStatus.BAD_REQUEST);
    }

    /**
     * 处理权限认证异常
     */
    @ExceptionHandler(SecurityException.class)
    public ResponseEntity<String> handleSecurityException(SecurityException ex, WebRequest request) {
        Result<Object> result = Result.fail(401, "认证失败: " + ex.getMessage());
        return new ResponseEntity<>(gson.toJson(result), HttpStatus.UNAUTHORIZED);
    }

    /**
     * 处理通用异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleGeneralException(Exception ex, WebRequest request) {
        ex.printStackTrace(); // 实际项目中应该使用日志记录
        Result<Object> result = Result.fail(500, "系统错误: " + ex.getMessage());
        return new ResponseEntity<>(gson.toJson(result), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}